package cn.com.gzheroli.bfw.web.system.controler.core;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.apache.ibatis.jdbc.SQL;
import org.apache.log4j.Logger;

import cn.com.gzheroli.auth.service.TSDataruleService;
import cn.com.gzheroli.bfw.pojo.base.TSBaseUser;
import cn.com.gzheroli.bfw.pojo.base.TSDepart;
import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.cache.SpringRedisCache;
import cn.com.gzheroli.core.common.entity.TreeBean;
import cn.com.gzheroli.core.common.model.json.AjaxJson;
import cn.com.gzheroli.core.common.model.json.ComboTree;
import cn.com.gzheroli.core.common.model.json.TreeGrid;
import cn.com.gzheroli.core.common.model.json.ValidForm;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.core.constant.Globals;
import cn.com.gzheroli.core.manager.Client;
import cn.com.gzheroli.core.util.NameHandler;
import cn.com.gzheroli.core.util.IdWorker;
import cn.com.gzheroli.core.util.LogUtil;
import cn.com.gzheroli.core.util.StringUtil;
import cn.com.gzheroli.core.util.oConvertUtils;
import cn.com.gzheroli.core.util.mybatis.SqlMapper;
import cn.com.gzheroli.rabbitmq.service.log.LogService;
import cn.com.gzheroli.service.bfw.DepartService;
import cn.com.gzheroli.service.bfw.UserService;
import cn.com.gzheroli.tag.core.DataGrid;
import cn.com.gzheroli.util.TagUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


/**
 * 部门信息处理类
 * 
 * 
 */
@Controller
@RequestMapping("/departController")
public class DepartController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(DepartController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private SystemService systemService;
	private String message;
	@Autowired
	private LogService logService;
	@Autowired
	private DepartService departService;
	@Autowired
	private CommonService commonService;
	@Autowired
	SqlMapper sqlMapper;
	@Autowired
    private SpringRedisCache cache;
	@Autowired
	  private TSDataruleService dataruleService;
	

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}



	/**
	 * easyuiAJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		/*CriteriaQuery cq = new CriteriaQuery(TSDepart.class, dataGrid);
		this.systemService.getDataGridReturn(cq, true);*/
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			dataGrid.setTotal(0);
			dataGrid.setResults(new ArrayList());
			TagUtil.datagrid(response, dataGrid);
			return;
		}
		TSUser user=client.getUser();
		List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
		Map dataMap =new HashMap();
		dataMap.put("pid", request.getParameter("id"));
		//String authSql=dataruleService.genSqlByModuleName("authUserSql","bu",user);	
		//dataMap.put("authSql", authSql);
		results =departService.getDepartList(dataMap);
		dataGrid.setTotal(results.size());
		dataGrid.setResults(results);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除部门
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(TSDepart depart, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		depart = commonService.getEntity(TSDepart.class, depart.getId());
		message = "部门: " + depart.getDepartName() + "被删除 成功";
		// 删除部门之前更新与之相关的实体
		//upEntity(depart);
		//commonService.delete(TSDepart.class,depart.getId());
		if(depart!=null){
		departService.delDepartCase(depart.getId());
		logService.addLogRoleauth(message, Globals.Log_Type_DEL,null, LogUtil.logReqMap(request));
		}
		j.setSuccess(true);
		j.setMsg(message);
		return j;
	}
	/**
	 * 级联更新部门级别编号，便于查询所有子部门
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "casedUpdateDeptLevelNo")
	@ResponseBody
	public synchronized AjaxJson casedUpdateDeptLevelNo(HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		departService.updateDeptLevelNoCased("","");
		j.setSuccess(true);
		j.setMsg("更新成功");
		return j;
	}
	/**
	 * 添加部门
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public synchronized AjaxJson save(TSDepart depart, HttpServletRequest request) {
		// 设置上级部门
		String pid = request.getParameter("parentId")==null?"":request.getParameter("parentId");
		if (pid.equals("")) {
			depart.setParentId("");
		}
		//
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(depart.getId())) {
			TSDepart olddepart=commonService.getEntity(TSDepart.class, depart.getId());
			boolean difPid=null!=olddepart.getParentId()&&!olddepart.getParentId().equals(depart.getParentId());
			if(difPid||depart.getLevelNo()==null||depart.getLevelNo().trim().equals("")){
				TSDepart pdepart=commonService.getEntity(TSDepart.class, pid);
				String sql="select LEVEL_NO  from T_S_DEPART where PARENT_ID=#{pid} and  (LEVEL_NO is not null or LEVEL_NO<>'')  order by LEVEL_NO desc";
				Map para=new HashMap();
				para.put("pid", pid);
				Map map=commonService.findOneForJdbc(sql,para );
				String pLevelNo=null==pdepart||pdepart.getLevelNo()==null?"":pdepart.getLevelNo();
				String levelNo=map==null||map.get("levelNo")==null?pLevelNo+"000":(String)map.get("levelNo");
				String newLevelNo=StringUtil.fillDepartLevel(pLevelNo,levelNo);
				depart.setLevelNo(newLevelNo);
			}
			message = "部门: " + depart.getDepartName() + "被更新成功";
			commonService.update(depart);
			logService.addLogRoleauth(message, Globals.Log_Type_UPDATE,null, LogUtil.logReqMap(request));
		} else {
			TSDepart pdepart=commonService.getEntity(TSDepart.class, pid);
			//String sql="select max(cast(ID as INTEGER)) ID from T_S_DEPART";
			String sql="select LEVEL_NO  from T_S_DEPART where PARENT_ID=#{pid} and (LEVEL_NO is not null or LEVEL_NO<>'')  order by LEVEL_NO desc";
			Map para=new HashMap();
			para.put("pid", pid);
			Map map=commonService.findOneForJdbc(sql,para );
			String pLevelNo=null==pdepart||pdepart.getLevelNo()==null?"":pdepart.getLevelNo();
			String levelNo=map==null||map.get("levelNo")==null?pLevelNo+"000":(String)map.get("levelNo");
			String newLevelNo=StringUtil.fillDepartLevel(pLevelNo,levelNo);
			depart.setLevelNo(newLevelNo);
			//BigDecimal idval=(BigDecimal)map.get("LEVEL_NO");
			//int id=idval.intValue()+1;
			//depart.setId(id+"");
			depart.setId(IdWorker.getFlowIdWorkerInstance().nextIdStr());
			message = "部门: " + depart.getDepartName() + "被添加成功";
			commonService.save(depart);
			logService.addLogRoleauth(message, Globals.Log_Type_INSERT,null, LogUtil.logReqMap(request));
		}
		
		return j;
	}
	
	@RequestMapping(params = "add")
	public ModelAndView add(TSDepart depart, HttpServletRequest req) {
		//List<TSDepart> departList = systemService.getList(TSDepart.class);
		List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
		Map dataMap =new HashMap();
		results =departService.getDepartList(dataMap);
		req.setAttribute("departList", results);
		if (StringUtil.isNotEmpty(depart.getId())) {
			//TSDepart tspDepart = new TSDepart();
			TSDepart tsDepart = new TSDepart();
			depart = commonService.getEntity(TSDepart.class, depart.getId());
			/*tspDepart.setId(depart.getId());
			tspDepart.setDepartname(depart.getDepartname());
			tsDepart.setTSPDepart(tspDepart);*/
			tsDepart.setParentId(depart.getId());
			tsDepart.setParentName(depart.getDepartName());
			req.setAttribute("depart", tsDepart);
		}
		return new ModelAndView("system/depart/depart");
	}
	/**
	 * 部门列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "update")
	public ModelAndView update(TSDepart depart, HttpServletRequest req) {
		//List<TSDepart> departList = systemService.getList(TSDepart.class);
		List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
		Map dataMap =new HashMap();
		results =departService.getDepartList(dataMap);
		req.setAttribute("departList", results);
		if (StringUtil.isNotEmpty(depart.getId())) {
			depart = departService.getDepart(depart.getId());
			req.setAttribute("depart", depart);
		}
		return new ModelAndView("system/depart/depart");
	}
	/**
	 * 获取部门信息
	 * 
	 * @return
	 */
	@RequestMapping(params = "getDepartData")
	@ResponseBody
	public AjaxJson getDepartData(TSDepart depart,HttpServletRequest request) {
		AjaxJson j=new AjaxJson();
		List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
		//Map dataMap =new HashMap();
		//results =departService.getDepartList(dataMap);
		//req.setAttribute("departList", results);
		if (StringUtil.isNotEmpty(depart.getId())) {
			depart = departService.getDepart(depart.getId());
		}
		j.setObj(depart);
		j.setSuccess(true);
		j.setMsg("获取成功");
		return j;
	}
	
	/**
	 * 父级权限列表
	 * 
	 * @param role
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 * @return
	 */
	@RequestMapping(params = "setPFunction")
	@ResponseBody
	public List<ComboTree> setPFunction(HttpServletRequest request, ComboTree comboTree) {
		//String parentid=request.getParameter("parentid")==null?"":request.getParameter("parentid");
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			return new ArrayList();
		}
		String selfId=request.getParameter("selfId");
		TSUser user=client.getUser();
		String parentid=comboTree.getId()==null?"":comboTree.getId();
		return departService.setPFunction(user, parentid, selfId);

	}
	/**
	 * 部门列表，树形展示
	 * @param request
	 * @param response
	 * @param treegrid
	 * @return
	 */
	@RequestMapping(params = "departgrid")
	@ResponseBody
	public  List<Map<String,Object>>  departgrid(TSDepart tSDepart,HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			return new ArrayList();
		}
		TSUser user=client.getUser();
		List<Map<String,Object>> treeGrids = new ArrayList<Map<String,Object>>();
		Map dataMap =new HashMap();
		dataMap.put("pid", request.getParameter("id"));
		//String authSql=dataruleService.genSqlByModuleName("authDepartSql","d",user);	
		//dataMap.put("authDepartSql", authSql);
		treeGrids =departService.getDepartList(dataMap);
		return treeGrids;
	}
	//----
	/**
	 * 方法描述:  查看成员列表
	 * 日    期： Dec 4, 2013-8:53:39 PM
	 * @param request
	 * @param departid
	 * @return 
	 * 返回类型： ModelAndView
	 */
	@RequestMapping(params = "userList")
	public ModelAndView userList(HttpServletRequest request, String departid) {
		request.setAttribute("departid", departid);
		return new ModelAndView("system/depart/departUserList");
	}
	
	/**
	 * 方法描述:  成员列表dataGrid
	 * 作    者： yiming.zhang
	 * 日    期： Dec 4, 2013-10:40:17 PM
	 * @param user
	 * @param request
	 * @param response
	 * @param dataGrid 
	 * 返回类型： void
	 */
	@RequestMapping(params = "userDatagrid")
	public void userDatagrid(TSUser user,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			dataGrid.setTotal(0);
			dataGrid.setResults(new ArrayList());
			TagUtil.datagrid(response, dataGrid);
			return;
		}
		TSUser curUser=client.getUser();
		Short[] userstate = new Short[] { Globals.User_Normal, Globals.User_ADMIN };
		String departid = oConvertUtils.getString(request.getParameter("departid"));
		String userName = oConvertUtils.getString(request.getParameter("userName"));
		String realName = oConvertUtils.getString(request.getParameter("realName"));
		// 上面的是用的hibernate
		Integer page =request.getParameter("page")==null?1:Integer.parseInt(request.getParameter("page"));
		Integer rows =request.getParameter("rows")==null?20:Integer.parseInt(request.getParameter("rows"));
		Integer start = Integer
				.valueOf((page.intValue() - 1) * rows.intValue()) + 1;
		Integer end = Integer.valueOf(page.intValue() * rows.intValue());
		HashMap parameter = new HashMap();
		if (!StringUtil.isEmpty(departid)) {
		parameter.put("departID", departid);
		}else{
			parameter.put("departID", user.getDepartId());
		}
		//parameter.put("status", userstate);
		parameter.put("userName",userName);
		parameter.put("realName", realName);
		parameter.put("maxResults", end.intValue());
		parameter.put("firstResult", start.intValue());
		parameter.put("beginRow", (page-1)*rows);//mysql
		parameter.put("pageSize", end.intValue() - start.intValue() + 1);
		//String authUserSql=dataruleService.genSqlByModuleName("authUserSql","tu",curUser);	
		//parameter.put("authUserSql", authUserSql);
		Long Acount = userService.selectUserAcount(parameter);
		//dataGrid.setResults(usermapper);
		dataGrid.setTotal(Acount.intValue());
		List<TSUser> userList=userService.getUserList(parameter);
		dataGrid.setResults(userList);
		TagUtil.datagrid(response, dataGrid);
	}
	//----
	
	/**
	 * 获取部门数结构
	 */
	@RequestMapping(params="getDepTree")
	@ResponseBody
	public List<TreeBean> getDepTree(String tid){
		List<TreeBean> tree=new ArrayList<TreeBean>();
		List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
		Map dataMap =new HashMap();
		dataMap.put("status", "1");
		if(tid==null)
			dataMap.put("pid", "");
		else {
			dataMap.put("pid", tid);
		}
		
		results =departService.getDepartList(dataMap);
		
		for(Map dep:results){
			TreeBean treeBean=new TreeBean();
			treeBean.setId(dep.get("id").toString());
			Object parentId=dep.get("id");
			
			if(parentId==null)
				treeBean.setPid("none");
			else
				treeBean.setPid(parentId.toString());
			String state=dep.get("state").toString();
			String departname=dep.get("departName")==null?"":dep.get("departName").toString();
			treeBean.setName(departname);
			if(state.equals("closed"))
				treeBean.setIsParent(true);
			else
				treeBean.setIsParent(false);
			tree.add(treeBean);
		}
		return tree;
	}
	@RequestMapping(params="getDepComboTree")
	@ResponseBody
	public AjaxJson comboxTreeGroup(HttpServletRequest request) throws Exception{
        String data=null;
        AjaxJson j=new AjaxJson();
        String parentid=request.getParameter("parentid")==null?"":request.getParameter("parentid");
        //JSONArray jsons =builderComboTree(parentid);
        //data=jsons.toString();    
        List<Map<String,Object>> deptTree=builderComboTree(parentid);
        j.setObj(deptTree);
        j.setSuccess(true);
        return j;
	}
	 public List<Map<String,Object>> builderComboTree(String parentid)throws Exception{
			Map para=new HashMap();
			if(parentid==null||parentid.equals(""))
				para.put("pid",null);
			else {
				para.put("pid", parentid);
			}
			para.put("status", "1");
			List<Map<String,Object>> departs=new ArrayList();
			if(parentid==null||parentid.equals("")){
				Map<String,Object> nor=new HashMap();
				nor.put("id", "");
				nor.put("text", "请选择");
				departs.add(nor);
			}
			
			departs.addAll(departService.getDepartList(para));
	        return departs;
	    }
	 @RequestMapping(params="getDepartTree")
		@ResponseBody
		public AjaxJson getDepartTree(HttpServletRequest request) throws Exception{
	        String data=null;
	        AjaxJson j=new AjaxJson();
	        String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
			Client client=cache.getCache(token, Client.class);
			if(client==null||client.getUser()==null){
				j.setSuccess(false);
				j.setMsg("尚未登录,请登录!");
				return j;
			}
			TSUser user=client.getUser();
	        String parentid=request.getParameter("parentid")==null?"":request.getParameter("parentid");
	        //JSONArray jsons =builderComboTree(parentid);
	        //data=jsons.toString();    
	        //List<Map<String,Object>> deptTree=builderComboTree(parentid);
	        Map para=new HashMap();
			if(parentid==null||parentid.equals(""))
				para.put("pid",null);
			else {
				para.put("pid", parentid);
			}
			para.put("status", "1");
			//String authDepartSql=dataruleService.genSqlByModuleName("authDepartSql","d",user);	
			//para.put("authDepartSql", authDepartSql);
			List<Map<String,Object>> deptTree=departService.getDepartList(para);
	        j.setObj(deptTree);
	        j.setSuccess(true);
	        return j;
		}
	 
		/*
		 * *****************部门管理操作****************************
		 */

		/**
		 * 部门列表页面跳转
		 * 
		 * @return
		 */
		@RequestMapping(params = "depart")
		public ModelAndView depart() {
			return new ModelAndView("system/depart/departList");
		}

		/**
		 * easyuiAJAX请求数据
		 * 
		 * @param request
		 * @param response
		 * @param dataGrid
		 * @param user
		 */

		@RequestMapping(params = "datagridDepart")
		public void datagridDepart(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
			/*CriteriaQuery cq = new CriteriaQuery(TSDepart.class, dataGrid);
			this.systemService.getDataGridReturn(cq, true);*/
			String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
			Client client=cache.getCache(token, Client.class);
			if(client==null||client.getUser()==null){
				dataGrid.setTotal(0);
				dataGrid.setResults(new ArrayList());
				TagUtil.datagrid(response, dataGrid);
				return;
			}
			TSUser user=client.getUser();
			Map para=new HashMap();
			//para.put("businessKey", businessKey);
			//String authSql=dataruleService.genSqlByModuleName("authUserSql","bu",user);	
			final String tableName = new NameHandler().getTableName(TSDepart.class.getSimpleName());
			SQL sql=new SQL();
			sql.SELECT("*");
			sql.FROM(tableName);
			//sql.WHERE(authSql);
			dataGrid=this.commonService.getDataGridReturn(dataGrid,TSDepart.class,sql.toString(),para,true);
			TagUtil.datagrid(response, dataGrid);
			;
		}

		/**
		 * 删除部门
		 * 
		 * @return
		 */
		@RequestMapping(params = "delDepart")
		@ResponseBody
		public AjaxJson delDepart(TSDepart depart, HttpServletRequest request) {
			AjaxJson j = new AjaxJson();
			depart = commonService.getEntity(TSDepart.class, depart.getId());
			message = "部门: " + depart.getDepartName() + "被删除 成功";
			commonService.delete(TSDepart.class,depart.getId());
			logService.addLogRoleauth(message, Globals.Log_Type_DEL, null,LogUtil.logReqMap(request));

			return j;
		}

		/**
		 * 添加部门
		 * 
		 * @param ids
		 * @return
		 */
		@RequestMapping(params = "saveDepart")
		@ResponseBody
		public AjaxJson saveDepart(TSDepart depart, HttpServletRequest request) {
			// 设置上级部门
			String pid = request.getParameter("parentId")==null?"":request.getParameter("parentId");
			if (pid.equals("")) {
				depart.setParentId("");
			}
			Map logMap=LogUtil.logReqMap(request);
			return departService.saveDepart(depart, pid, logMap);
		}

		/**
		 * 部门列表页面跳转
		 * 
		 * @return
		 */
		@RequestMapping(params = "addorupdateDepart")
		public ModelAndView addorupdateDepart(TSDepart depart, HttpServletRequest req) {
			List<TSDepart> departList = commonService.loadAll(TSDepart.class);
			req.setAttribute("departList", departList);
			if (depart.getId() != null) {
				depart = commonService.getEntity(TSDepart.class, depart.getId());
				req.setAttribute("depart", depart);
			}
			return new ModelAndView("system/depart/depart");
		}
		@RequestMapping(params = "checkdepart")
		@ResponseBody
		public ValidForm checkdepart(HttpServletRequest request) {
			ValidForm v = new ValidForm();
			String param=oConvertUtils.getString(request.getParameter("param"));
			String name=oConvertUtils.getString(request.getParameter("name"));
			String parentId=oConvertUtils.getString(request.getParameter("parentId"));
			String departName=oConvertUtils.getString(request.getParameter("departName"));
			
			Map para=new HashMap();
			para.put("parentId", parentId);
			para.put("departName", param);
			String sql="select count(*) from T_S_DEPART d where d.DEPART_NAME=#{departName} ";
			if(null!=parentId&&!parentId.trim().equals(""))
				sql=sql+"and d.PARENT_ID=#{parentId}";
			Long typeSize=commonService.getCountForJdbc(sql, para);
			if(typeSize.intValue()>0&&!param.equals(departName))
			{
				v.setInfo("部门名称已经已存在");
				v.setStatus("n");
			}
			return v;
		}
}
